import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'
import Cookies from 'js-cookie'

// 公共页面
const Login = () => import('../views/auth/Login.vue')
const Register = () => import('../views/auth/Register.vue')
const Home = () => import('../views/Home.vue')

// 管理员页面
const AdminLayout = () => import('../views/admin/AdminLayout.vue')
const AdminDashboard = () => import('../views/admin/Dashboard.vue')
const AdminFeedbacks = () => import('../views/admin/Feedbacks.vue')
const AdminGridMembers = () => import('../views/admin/GridMembers.vue')
const AdminStatistics = () => import('../views/admin/Statistics.vue')
const AdminSettings = () => import('../views/admin/Settings.vue')

// 网格员页面
const GridLayout = () => import('../views/grid/GridLayout.vue')
const GridDashboard = () => import('../views/grid/Dashboard.vue')
const GridTasks = () => import('../views/grid/Tasks.vue')
const GridConfirm = () => import('../views/grid/Confirm.vue')
const GridStatistics = () => import('../views/grid/Statistics.vue')

// 公众监督员页面
const SupervisorLayout = () => import('../views/supervisor/SupervisorLayout.vue')
const SupervisorDashboard = () => import('../views/supervisor/Dashboard.vue')
const SupervisorSubmit = () => import('../views/supervisor/Submit.vue')
const SupervisorHistory = () => import('../views/supervisor/History.vue')

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'register',
    component: Register,
    meta: { requiresAuth: false }
  },
  
  // 管理员路由
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, roles: ['ADMIN'] },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'admin-dashboard',
        component: AdminDashboard,
        meta: { title: '管理员仪表板' }
      },
      {
        path: 'feedbacks',
        name: 'admin-feedbacks',
        component: AdminFeedbacks,
        meta: { title: '反馈管理' }
      },
      {
        path: 'grid-members',
        name: 'admin-grid-members',
        component: AdminGridMembers,
        meta: { title: '网格员管理' }
      },
      {
        path: 'statistics',
        name: 'admin-statistics',
        component: AdminStatistics,
        meta: { title: '统计报表' }
      },
      {
        path: 'settings',
        name: 'admin-settings',
        component: AdminSettings,
        meta: { title: '系统设置' }
      }
    ]
  },
  
  // 网格员路由
  {
    path: '/grid',
    component: GridLayout,
    meta: { requiresAuth: true, roles: ['GRID_MEMBER'] },
    children: [
      {
        path: '',
        redirect: '/grid/dashboard'
      },
      {
        path: 'dashboard',
        name: 'grid-dashboard',
        component: GridDashboard,
        meta: { title: '网格员仪表板' }
      },
      {
        path: 'tasks',
        name: 'grid-tasks',
        component: GridTasks,
        meta: { title: '指派任务' }
      },
      {
        path: 'confirm',
        name: 'grid-confirm',
        component: GridConfirm,
        meta: { title: '确认数据' }
      },
      {
        path: 'statistics',
        name: 'grid-statistics',
        component: GridStatistics,
        meta: { title: '工作统计' }
      }
    ]
  },
  
  // 公众监督员路由
  {
    path: '/supervisor',
    component: SupervisorLayout,
    meta: { requiresAuth: true, roles: ['SUPERVISOR'] },
    children: [
      {
        path: '',
        redirect: '/supervisor/dashboard'
      },
      {
        path: 'dashboard',
        name: 'supervisor-dashboard',
        component: SupervisorDashboard,
        meta: { title: '监督员仪表板' }
      },
      {
        path: 'submit',
        name: 'supervisor-submit',
        component: SupervisorSubmit,
        meta: { title: '提交反馈' }
      },
      {
        path: 'history',
        name: 'supervisor-history',
        component: SupervisorHistory,
        meta: { title: '历史记录' }
      }
    ]
  },
  
  // 404页面 - Vue Router 4使用正则表达式
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('../views/error/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 环保公众监督系统`
  } else {
    document.title = '环保公众监督系统'
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const token = Cookies.get('token')
    const userRole = Cookies.get('userRole')
    
    if (!token) {
      // 没有token，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && !to.meta.roles.includes(userRole)) {
      // 权限不足，跳转到首页
      next('/')
      return
    }
    
    // 验证token是否有效
    try {
      const valid = await store.dispatch('user/validateToken')
      if (valid) {
        next()
      } else {
        // token无效，清除并跳转到登录页
        await store.dispatch('user/logout')
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
    } catch (error) {
      // 验证失败，跳转到登录页
      await store.dispatch('user/logout')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
